package com.css.bjdt_core.reportPrepare.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.bjdt_core.executive.report.ReportRequest;
import com.css.bjdt_core.reportFill.entity.ViewUnitTemplate;
import com.css.bjdt_core.reportPrepare.entity.HigherLevelLssuedRange;
import com.css.bjdt_core.reportPrepare.entity.RptBatch;
import com.css.bjdt_core.reportPrepare.entity.RptBatchDzzRel;
import com.css.bjdt_core.reportPrepare.entity.RptBatchTemplateRel;
import com.css.bjdt_core.reportPrepare.entity.RptBatchUnitRel;
import com.css.bjdt_core.reportPrepare.entity.RptGroup;
import com.css.bjdt_core.reportPrepare.entity.RptUnit;
import com.css.bjdt_core.reportPrepare.entity.RptUnitAnnualRel;
import com.css.bjdt_core.reportPrepare.entity.ViewRptGroupTemplate;
import com.css.bjdt_core.util.CommonUtil;

@Service
public class RptDealWithService {
	@Autowired
	private Dao dao;

	public RptBatchUnitRel queryBatchUnitRel(String unitId) {
		return dao.fetch(RptBatchUnitRel.class, Cnd.where("UNIT_ID", "=", unitId));
	}

	public RptBatch queryBatch(String batchId) {
		return dao.fetch(RptBatch.class, Cnd.where("BATCH_ID", "=", batchId));
	}

	//改变单位的上报状态
	public void updateBatchState(String batchId, String reportState, String examineType) {
		String strSql = "update RPT_BATCH set REPORT_STATE = @reportState,EXAMINE_TYPE = @examineType where BATCH_ID = @batchId";
		Sql sql = Sqls.create(strSql);
		sql.params().set("reportState", reportState).set("batchId", batchId).set("examineType", examineType);
		dao.execute(sql);
	}

	//改变单位的上报状态
	public void updateReportState(String batchId, String reportState) {
		String strSql = "update RPT_BATCH set REPORT_STATE = @reportState where BATCH_ID = @batchId";
		Sql sql = Sqls.create(strSql);
		sql.params().set("reportState", reportState).set("batchId", batchId);
		dao.execute(sql);
	}

	//改变单位EXAMINE_TYPE状态
	public void updateBatchExamineType(String batchId, String examineType) {
		String strSql = "update RPT_BATCH set EXAMINE_TYPE = @examineType where BATCH_ID = @batchId";
		Sql sql = Sqls.create(strSql);
		sql.params().set("examineType", examineType).set("batchId", batchId);
		dao.execute(sql);
	}

	public void saveBatch(RptBatch batch) {
		if (StringUtils.isEmpty(batch.getId())) {
			batch.setId(CommonUtil.getUUID());
		}
		dao.insert(batch);
	}

	public void updateBatch(RptBatch batch) {
		dao.updateIgnoreNull(batch);
	}

	public void saveBatchUnitRel(RptBatchUnitRel batchUnitRel) {
		dao.insert(batchUnitRel);
	}

	//得到当前单位下，当前年度的所有报表信息
	public List<ViewRptGroupTemplate> getTemplateByAnnual(String annualId) {
		//根据年度获得当前报表组(2是汇总表，3是通用表)
		/*SqlExpressionGroup g1 = Cnd.exps("GRPTYPE", "=", "2");
		SqlExpressionGroup g2 = Cnd.exps("GRPTYPE", "=", "3");*/
		List<RptGroup> rptGroupList = dao.query(RptGroup.class, Cnd.where("ANNUALID", "=", annualId).asc("ORDERID"));

		List<String> strList = new ArrayList<String>();

		for (RptGroup rptGroup : rptGroupList) {
			strList.add(rptGroup.getGroupId());
		}

		List<ViewRptGroupTemplate> viewRptGroupTemplateList = new ArrayList<ViewRptGroupTemplate>();

		//根据报表组ID查询出所有报表
		if (strList.size() != 0) {
			viewRptGroupTemplateList = dao.query(ViewRptGroupTemplate.class,
					Cnd.where("GROUPID", "in", strList).asc("ORDERID").asc("TEMPLATEORDERID"));
		}

		for (ViewRptGroupTemplate viewRptGroupTemplate : viewRptGroupTemplateList) {
			viewRptGroupTemplate.setPid(viewRptGroupTemplate.getGroupId());
			viewRptGroupTemplate.setIsGroupRpt("1");
		}

		for (RptGroup rptGroup : rptGroupList) {
			ViewRptGroupTemplate viewRptGroupTemplate = new ViewRptGroupTemplate();
			viewRptGroupTemplate.setAnnualId(rptGroup.getAnnualId());
			viewRptGroupTemplate.setDescription(rptGroup.getDescription());
			viewRptGroupTemplate.setGroupId(rptGroup.getGroupId());
			viewRptGroupTemplate.setGrptype(rptGroup.getGrptype());
			viewRptGroupTemplate.setName(rptGroup.getName());
			viewRptGroupTemplate.setOrderId(rptGroup.getOrderId());
			viewRptGroupTemplate.setPid("0");
			viewRptGroupTemplate.setTemplateId(rptGroup.getGroupId());
			viewRptGroupTemplate.setTemplateName(rptGroup.getName());
			viewRptGroupTemplate.setIsGroupRpt("0");
			viewRptGroupTemplateList.add(viewRptGroupTemplate);
		}

		return viewRptGroupTemplateList;
	}

	public List<RptBatchTemplateRel> queryBatchTemplateRel(String batchId) {
		return dao.query(RptBatchTemplateRel.class, Cnd.where("BATCH_ID", "=", batchId));
	}

	public void saveBatchTemplateRel(List<RptBatchTemplateRel> batchTemplateRelList) {
		dao.insert(batchTemplateRelList);
	}

	public void clearBatchTemplateRel(String batchId) {
		dao.clear(RptBatchTemplateRel.class, Cnd.where("BATCH_ID", "=", batchId));
	}

	public RptBatchTemplateRel getARptBatchTemplateRel(String batchId, String templateId) {
		return dao.fetch(RptBatchTemplateRel.class,
				Cnd.where("BATCH_ID", "=", batchId).and("TEMPLATE_ID", "=", templateId));
	}

	//需要高阳根据新表重新修改视图和逻辑
	public List<ViewUnitTemplate> getViewUnitTemplateRelByAnnualAndUnit(String batchId) {
		List<ViewUnitTemplate> unitTemplates = dao.query(ViewUnitTemplate.class,
				Cnd.where("BATCH_ID", "=", batchId).asc("ORDERID").asc("TEMPLATEORDERID"));
		return unitTemplates;
	}

	public List<RptBatchDzzRel> queryBatchDzzRel(String batchId) {
		return dao.query(RptBatchDzzRel.class, Cnd.where("BATCH_ID", "=", batchId));
	}

	public List<String> getValidDzzIdForSummary(String dzzId, final String annualId) {
		String strSql = "select a.DDZ_ID from RPT_BATCH_DZZ_R a, t_m_zzinfo b, RPT_BATCH c where a.DDZ_ID = b.DZZID and a.BATCH_ID = c.BATCH_ID and b.sjdzzid = @dzzId "
				+ " and b.DELETEFLAG = '0' and a.ANNUAL_ID = @annualId and c.REPORT_STATE in ('1', '2', '3', '100') order by b.ORDERNUM asc ";
		Sql sql = Sqls.create(strSql);
		sql.params().set("dzzId", dzzId).set("annualId", annualId);
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				List<String> res = new ArrayList<>();
				while (rs.next()) {
					res.add(rs.getString("DDZ_ID"));
				}
				return res;
			}
		});
		dao.execute(sql);
		return sql.getList(String.class);
	}

	public RptBatchDzzRel getARptBatchDzzRel(String dzzId, String annualId) {
		return dao.fetch(RptBatchDzzRel.class, Cnd.where("DDZ_ID", "=", dzzId).and("ANNUAL_ID", "=", annualId));
	}

	//因为有重复数据，现在把这个单位下所有的全部找出去
	public List<RptBatchDzzRel> getAllRptBatchDzzRel(String dzzId, String annualId) {
		return dao.query(RptBatchDzzRel.class, Cnd.where("DDZ_ID", "=", dzzId).and("ANNUAL_ID", "=", annualId));
	}

	public void clearBatchDzzRel(String batchId) {
		dao.clear(RptBatchDzzRel.class, Cnd.where("BATCH_ID", "=", batchId));
	}

	public void saveBatchDzzRelList(List<RptBatchDzzRel> batchDzzRelList) {
		dao.insert(batchDzzRelList);
	}

	//新增单个批次和党组织之间的关系
	public void saveABatchDzzRel(RptBatchDzzRel rptBatchDzzRel) {
		dao.insert(rptBatchDzzRel);
	}

	public ReportRequest buildBatchRequest(String batchId) {
		RptBatch batch = queryBatch(batchId);
		RptBatchUnitRel batchUnitRel = dao.fetch(RptBatchUnitRel.class, Cnd.where("BATCH_ID", "=", batchId));
		String unitId = batchUnitRel.getUnitId();
		RptUnit unit = dao.fetch(RptUnit.class, unitId);
		RptUnitAnnualRel unitAnnualRel = dao.fetch(RptUnitAnnualRel.class, Cnd.where("UNIT_ID", "=", unitId));
		List<RptBatchDzzRel> batchDzzRels = queryBatchDzzRel(batchId);
		List<RptBatchTemplateRel> batchTemplateRel = queryBatchTemplateRel(batchId);
		List<String> dzzIds = new ArrayList<String>(batchDzzRels.size());
		List<String> templateIds = new ArrayList<String>(batchTemplateRel.size());
		for (RptBatchDzzRel rel : batchDzzRels) {
			dzzIds.add(rel.getDzzId());
		}
		for (RptBatchTemplateRel rel : batchTemplateRel) {
			templateIds.add(rel.getTemplateId());
		}
		ReportRequest request = new ReportRequest();
		request.setAnnualId(unitAnnualRel.getAnnualId());
		request.setStartTime(batch.getStartTime());
		request.setEndTime(batch.getEndTime());
		request.setReportDzzId(unitAnnualRel.getDzzId());
		request.setReportDzzName(unit.getFullName());
		request.setReportMan(unit.getRelMan());
		request.setDzzIds(filterDzz(dzzIds.toArray(new String[0])));
		request.setTemplateIds(templateIds);
		request.setSyn(false);
		return request;
	}

	private List<String> filterDzz(String[] dzzIds) {
		List<String> list = new ArrayList<String>();
		String[] array = { "621", "631", "632" };
		for (String dzzId : dzzIds) {
			if (ArrayUtils.contains(array, dzzId)) {
				list.add(dzzId);
			}
		}
		return list;
	}

	public void updateARptBatchTemplateRel(RptBatchTemplateRel rptBatchTemplateRel) {
		String strSql = "update RPT_BATCH_TEMPLATE_R set EXAMINE_STATE = @examineState,VALIDATION_STATE = @validationState where BATCH_ID = @batchId";
		Sql sql = Sqls.create(strSql);
		sql.params().set("examineState", rptBatchTemplateRel.getExamineState())
				.set("batchId", rptBatchTemplateRel.getId())
				.set("validationState", rptBatchTemplateRel.getValidationState());
		dao.execute(sql);
	}

	public void updateRptBatchTemplateRelByBatchId(String batchId, String examineState, String validationState) {
		String strSql = "update RPT_BATCH_TEMPLATE_R set EXAMINE_STATE = @examineState,VALIDATION_STATE = @validationState where BATCH_ID = @batchId";
		Sql sql = Sqls.create(strSql);
		sql.params().set("examineState", examineState).set("batchId", batchId).set("validationState", validationState);
		dao.execute(sql);
	}

	public void updateARptBatchTemplateRelByTemplateId(String templateId, String batchId, String examineState,
			String validationState) {
		String strSql = "update RPT_BATCH_TEMPLATE_R set EXAMINE_STATE = @examineState,VALIDATION_STATE = @validationState where BATCH_ID = @batchId and TEMPLATE_ID = @templateId";
		Sql sql = Sqls.create(strSql);
		sql.params().set("examineState", examineState).set("batchId", batchId).set("validationState", validationState)
				.set("templateId", templateId);
		dao.execute(sql);
	}

	public void updateARptBatchTemplateRelByTemplateIds(List<String> templateIds, String batchId, String examineState,
			String validationState) {
		String strSql = "update RPT_BATCH_TEMPLATE_R set EXAMINE_STATE = @examineState,VALIDATION_STATE = @validationState where BATCH_ID = @batchId and TEMPLATE_ID in ( $templateIds )";
		Sql sql = Sqls.create(strSql);
		sql.params().set("examineState", examineState).set("batchId", batchId).set("validationState", validationState);
		sql.vars().set("templateIds", CommonUtil.convertIDList(templateIds));
		dao.execute(sql);
	}

	public ViewRptGroupTemplate getAViewRptGroupTemplate(String templateId) {
		return dao.fetch(ViewRptGroupTemplate.class, Cnd.where("TEMPLATEID", "=", templateId));
	}

	//是否下发过报表
	public boolean isLssuedTemplate(String dzzId, String annualId) {
		RptBatchDzzRel rptBatchDzzRel = getARptBatchDzzRel(dzzId, annualId);
		//如果有记录，说明该单位已经下发过报表，如果没记录说明还未下发过报表
		if (null == rptBatchDzzRel) {
			return true;
		} else {
			return false;
		}
		//List<RptBatchTemplateRel> rptBatchTemplateRelList = queryBatchTemplateRel(rptBatchDzzRel.getId());
	}

	public List<HigherLevelLssuedRange> getHigherLevelRange(String batchId) {
		List<HigherLevelLssuedRange> higherLevelLssuedRangeList = dao.query(HigherLevelLssuedRange.class,
				Cnd.where("BATCH_ID", "=", batchId));
		return higherLevelLssuedRangeList;
	}
}
